/*******************************************
Module: zt_list.c
E-Mail: 24zhutian@gmail.com
Notices: Copyright (c) 2007-2011 ls
*******************************************/
#include "zt_config.h"
#include "zt_list.h"

ZT_API void zt_list_add_head(zt_list_t *list,zt_list_node_t *node)
{
	if(list->head==NULL){
		list->head=list->tail=node;
		node->prev=node->next=NULL;
	}
	else{
		node->prev=NULL;
		node->next=list->head;
		list->head->prev=node;
		list->head=node;
	}
 
	list->siz++;
}
 
ZT_API void zt_list_add_tail(zt_list_t *list,zt_list_node_t *node)
{
	if(list->head==NULL){
		list->head=list->tail=node;
		node->prev=node->next=NULL;
	}
	else{
		node->prev=list->tail;
		node->next=NULL;
		list->tail->next=node;
		list->tail=node;
	} 
	list->siz++;
}
 
ZT_API void zt_list_add_before(zt_list_t *list,zt_list_node_t *old,zt_list_node_t *node)
{
	node->next=old;
	node->prev=old->prev;
	if(list->head==old){
		list->head=node;
	}
	if(node->prev!=NULL){
		node->prev->next=node;
	}
	if(node->next!=NULL){
		node->next->prev=node;
	}
	list->siz++;
}
 
ZT_API void zt_list_add_after(zt_list_t *list,zt_list_node_t *old,zt_list_node_t *node)
{
	node->prev=old;
	node->next=old->next;
	if(list->tail==old){
		list->tail=node;
	}
	if(node->prev!=NULL){
		node->prev->next=node;
	}
	if(node->next!=NULL){
		node->next->prev=node;
	}
	list->siz++;
}
 
ZT_API zt_list_node_t* zt_list_find(zt_list_t *list,void *key,int (*ZT_LIST_CMP)(void *,void *))
{
	zt_list_node_t *node=NULL;
	
	zt_list_for_each(list,node){
		if(ZT_LIST_CMP(node->data,key)==0){
			return(node);
		}
	}
	return(NULL);
}

ZT_API void zt_list_del(zt_list_t *list,zt_list_node_t *node)
{
	if(node->prev==NULL){
		list->head=node->next;
	}
	else{
		node->prev->next=node->next;
	}
	if(node->next==NULL){
		list->tail=node->prev;
	}
	else{
		node->next->prev=node->prev;
	}
	list->siz--;
}

ZT_API int zt_list_int_cmp(void *n,void *k)
{
	return(*((zt_int_t *)n)-*((zt_int_t *)k));
}

ZT_API int zt_list_uint_cmp(void *n,void *k)
{
	return(*((zt_uint_t *)n)-*((zt_uint_t *)k));
}

ZT_API zt_int64_t zt_list_int64_cmp(void *n,void *k)
{
	return(*((zt_int64_t *)n)-*((zt_int64_t *)k));
}

ZT_API zt_int64_t zt_list_uint64_cmp(void *n,void *k)
{
	return(*((zt_uint64_t *)n)-*((zt_uint64_t *)k));
}

ZT_API int zt_list_str_cmp(void *n,void *k)
{
	register u_char *s1=(u_char *)n,*s2=(u_char *)k;
	
	while (*s1 == *s2++){
		if (*s1++ == 0){
			return (0);
		}
	}
	return (*s1 - *--s2);
}